from dash import Input, Output, State, callback_context, dcc, html
import dash
from flask_login import current_user
from models import *
from server import server
import pandas as pd
from sqlalchemy import func, and_, or_
from datetime import datetime


def register_opdb_callbacks(dash_app):
    """注册数据库操作相关的回调函数"""
    
    # 加载医院下拉列表
    @dash_app.callback(
        Output('opdb-hospital-dropdown', 'options'),
        [Input('opdb-refresh-button', 'n_clicks')]
    )
    def load_hospitals(_):
        with server.app_context():
            try:
                hospitals = db.session.query(Assets.org_name).filter(
                    Assets.is_active == True,
                    Assets.org_name.isnot(None),
                    Assets.org_name != ''
                ).distinct().all()
                return [{'label': hospital[0], 'value': hospital[0]} for hospital in hospitals]
            except Exception as e:
                print(f"数据库错误：{str(e)}")
                return []

    # 根据选择的医院加载科室
    @dash_app.callback(
        Output('opdb-department-dropdown', 'options'),
        [Input('opdb-hospital-dropdown', 'value')]
    )
    def load_departments(hospital):
        if not hospital:
            return []
        
        with server.app_context():
            departments = db.session.query(Assets.department_name).filter(
                Assets.org_name == hospital,
                Assets.is_active == True,
                Assets.department_name.isnot(None),
                Assets.department_name != ''
            ).distinct().all()
            return [{'label': dept[0], 'value': dept[0]} for dept in departments]

    # 根据选择的医院和科室加载设备类型
    @dash_app.callback(
        Output('opdb-category-dropdown', 'options'),
        [Input('opdb-hospital-dropdown', 'value'),
         Input('opdb-department-dropdown', 'value')]
    )
    def load_categories(hospital, department):
        filters = [Assets.is_active == True, 
                  Assets.category.isnot(None), 
                  Assets.category != '']
        
        if hospital:
            filters.append(Assets.org_name == hospital)
        if department:
            filters.append(Assets.department_name == department)
            
        with server.app_context():
            categories = db.session.query(Assets.category).filter(
                *filters
            ).distinct().all()
            return [{'label': cat[0], 'value': cat[0]} for cat in categories]
    
    # 查询资产数据
    @dash_app.callback(
        [Output('opdb-result-table', 'data'),
         Output('opdb-result-table', 'columns'),
         Output('opdb-error-message', 'children'),
         Output('opdb-error-message', 'style')],
        [Input('opdb-search-button', 'n_clicks')],
        [State('opdb-hospital-dropdown', 'value'),
         State('opdb-department-dropdown', 'value'),
         State('opdb-category-dropdown', 'value'),
         State('opdb-asset-code', 'value'),
         State('opdb-asset-name', 'value'),
         State('opdb-query-type', 'value')]
    )
    def search_assets(n_clicks, hospital, department, category, asset_code, asset_name, query_type):
        if not n_clicks:
            return [], [], "", {'display': 'none'}
        
        # 验证至少有一个查询条件
        if not any([hospital, department, category, asset_code, asset_name]):
            return [], [], "请至少输入一个查询条件", {'display': 'block'}
        
        try:
            with server.app_context():
                # 根据查询类型选择表
                if query_type == 'assets':
                    query = db.session.query(Assets)
                    filters = [Assets.is_active == True]
                    
                    if hospital:
                        filters.append(Assets.org_name == hospital)
                    if department:
                        filters.append(Assets.department_name == department)
                    if category:
                        filters.append(Assets.category == category)
                    if asset_code:
                        filters.append(Assets.asset_code.like(f"%{asset_code}%"))
                    if asset_name:
                        filters.append(Assets.asset_name.like(f"%{asset_name}%"))
                    
                    results = query.filter(*filters).all()
                    
                    if not results:
                        return [], [], "未找到符合条件的资产", {'display': 'block'}
                    
                    # 转换为DataFrame以便于处理
                    data = []
                    for asset in results:
                        data.append({
                            'asset_id': asset.asset_id,
                            'asset_code': asset.asset_code,
                            'asset_name': asset.asset_name,
                            'org_name': asset.org_name,
                            'department_name': asset.department_name,
                            'category': asset.category,
                            'price': asset.price,
                            'purchase_date': str(asset.purchase_date) if asset.purchase_date else "",
                            'brand': asset.brand,
                            'standard': asset.standard,
                            'service_life': asset.service_life
                        })
                    
                    # 创建表格列
                    columns = [
                        {'name': '资产ID', 'id': 'asset_id'},
                        {'name': '资产编号', 'id': 'asset_code'},
                        {'name': '资产名称', 'id': 'asset_name'},
                        {'name': '医院名称', 'id': 'org_name'},
                        {'name': '科室', 'id': 'department_name'},
                        {'name': '设备类型', 'id': 'category'},
                        {'name': '价格(万元)', 'id': 'price'},
                        {'name': '购买日期', 'id': 'purchase_date'},
                        {'name': '品牌', 'id': 'brand'},
                        {'name': '型号', 'id': 'standard'},
                        {'name': '使用年限', 'id': 'service_life'}
                    ]
                    
                    return data, columns, "", {'display': 'none'}
                
                elif query_type == 'repairs':
                    query = db.session.query(RepairRecords)
                    filters = [RepairRecords.is_active == True]
                    
                    if hospital:
                        filters.append(RepairRecords.医院名称 == hospital)
                    if department:
                        filters.append(RepairRecords.所属科室 == department)
                    if asset_code:
                        filters.append(RepairRecords.资产编号.like(f"%{asset_code}%"))
                    if asset_name:
                        filters.append(RepairRecords.设备名称.like(f"%{asset_name}%"))
                    
                    results = query.filter(*filters).all()
                    
                    if not results:
                        return [], [], "未找到符合条件的维修记录", {'display': 'block'}
                    
                    # 转换为DataFrame以便于处理
                    data = []
                    for repair in results:
                        data.append({
                            'id': repair.id,
                            'asset_code': repair.资产编号,
                            'asset_name': repair.设备名称,
                            'org_name': repair.医院名称,
                            'department_name': repair.所属科室,
                            'category': repair.通用类型,
                            'fault_desc': repair.故障描述,
                            'repair_status': repair.维修状态,
                            'repair_date': str(repair.报修时间) if repair.报修时间 else "",
                            'repair_content': repair.维修内容
                        })
                    
                    # 创建表格列
                    columns = [
                        {'name': '维修ID', 'id': 'id'},
                        {'name': '资产编号', 'id': 'asset_code'},
                        {'name': '设备名称', 'id': 'asset_name'},
                        {'name': '医院名称', 'id': 'org_name'},
                        {'name': '科室', 'id': 'department_name'},
                        {'name': '设备类型', 'id': 'category'},
                        {'name': '故障描述', 'id': 'fault_desc'},
                        {'name': '维修状态', 'id': 'repair_status'},
                        {'name': '报修日期', 'id': 'repair_date'},
                        {'name': '维修内容', 'id': 'repair_content'}
                    ]
                    
                    return data, columns, "", {'display': 'none'}
                
                else:
                    return [], [], "不支持的查询类型", {'display': 'block'}
                
        except Exception as e:
            print(f"查询错误: {str(e)}")
            return [], [], f"查询出错: {str(e)}", {'display': 'block'}
    
    # 添加/更新资产记录
    @dash_app.callback(
        [Output('opdb-update-message', 'children'),
         Output('opdb-update-message', 'style')],
        [Input('opdb-submit-button', 'n_clicks')],
        [State('opdb-asset-code-input', 'value'),
         State('opdb-asset-name-input', 'value'),
         State('opdb-hospital-input', 'value'),
         State('opdb-department-input', 'value'),
         State('opdb-category-input', 'value'),
         State('opdb-price-input', 'value'),
         State('opdb-purchase-date-input', 'value'),
         State('opdb-brand-input', 'value'),
         State('opdb-standard-input', 'value'),
         State('opdb-service-life-input', 'value'),
         State('opdb-operation-type', 'value')]
    )
    def update_asset(n_clicks, asset_code, asset_name, hospital, department, 
                    category, price, purchase_date, brand, standard, service_life, operation_type):
        if not n_clicks:
            return "", {'display': 'none'}
        
        # 验证必填字段
        if not all([asset_code, asset_name, hospital, department]):
            return "资产编号、资产名称、医院和科室为必填项", {'display': 'block', 'color': 'red'}
        
        try:
            with server.app_context():
                if operation_type == 'add':
                    # 检查资产编号是否已存在
                    existing_asset = db.session.query(Assets).filter(
                        Assets.asset_code == asset_code,
                        Assets.is_active == True
                    ).first()
                    
                    if existing_asset:
                        return f"资产编号 {asset_code} 已存在", {'display': 'block', 'color': 'red'}
                    
                    # 创建新资产
                    new_asset = Assets(
                        asset_code=asset_code,
                        asset_name=asset_name,
                        org_name=hospital,
                        department_name=department,
                        category=category,
                        price=float(price) if price else 0,
                        purchase_date=datetime.strptime(purchase_date, '%Y-%m-%d').date() if purchase_date else None,
                        brand=brand,
                        standard=standard,
                        service_life=int(service_life) if service_life else 0,
                        is_active=True
                    )
                    
                    db.session.add(new_asset)
                    db.session.commit()
                    return f"成功添加资产: {asset_name}", {'display': 'block', 'color': 'green'}
                
                elif operation_type == 'update':
                    # 查找要更新的资产
                    asset = db.session.query(Assets).filter(
                        Assets.asset_code == asset_code,
                        Assets.is_active == True
                    ).first()
                    
                    if not asset:
                        return f"未找到资产编号为 {asset_code} 的资产", {'display': 'block', 'color': 'red'}
                    
                    # 更新资产信息
                    asset.asset_name = asset_name
                    asset.org_name = hospital
                    asset.department_name = department
                    asset.category = category
                    asset.price = float(price) if price else asset.price
                    asset.purchase_date = datetime.strptime(purchase_date, '%Y-%m-%d').date() if purchase_date else asset.purchase_date
                    asset.brand = brand
                    asset.standard = standard
                    asset.service_life = int(service_life) if service_life else asset.service_life
                    
                    db.session.commit()
                    return f"成功更新资产: {asset_name}", {'display': 'block', 'color': 'green'}
                
                elif operation_type == 'delete':
                    # 查找要删除的资产
                    asset = db.session.query(Assets).filter(
                        Assets.asset_code == asset_code,
                        Assets.is_active == True
                    ).first()
                    
                    if not asset:
                        return f"未找到资产编号为 {asset_code} 的资产", {'display': 'block', 'color': 'red'}
                    
                    # 逻辑删除（设置is_active为False）
                    asset.is_active = False
                    db.session.commit()
                    return f"成功删除资产: {asset_name}", {'display': 'block', 'color': 'green'}
                
                else:
                    return "不支持的操作类型", {'display': 'block', 'color': 'red'}
                
        except Exception as e:
            print(f"更新错误: {str(e)}")
            return f"操作失败: {str(e)}", {'display': 'block', 'color': 'red'}

# 点击组织链接显示模态窗口
    @dash_app.callback(
        [Output('org-info-modal', 'style'),
         Output('org-modal-title', 'children'),
         Output('org-info-content', 'children')],
        [Input('hospital-count-link', 'n_clicks')],  # 保持只有一个 Input
        prevent_initial_call=True
    )
    def show_org_modal(n_clicks):  # 修改：只接收一个参数 n_clicks
        import sys
        print("DEBUG: 回调函数被调用", file=sys.stderr)
        
        # 获取触发回调的组件ID
        ctx = callback_context
        if not ctx.triggered or not n_clicks: # 检查 n_clicks 是否有值
            print("DEBUG: 回调未触发或无点击", file=sys.stderr)
            return dash.no_update # 使用 dash.no_update 避免不必要的更新
            
        trigger_id = ctx.triggered[0]['prop_id'].split('.')[0]
        print(f"DEBUG: 触发回调的组件ID: {trigger_id}", file=sys.stderr)
        
        # 确保触发的是 hospital-count-link
        if trigger_id == 'hospital-count-link':
            # 查询所有Organizations记录
            with server.app_context():
                try:
                    # 从数据库获取所有组织信息
                    orgs = Organizations.query.filter(Organizations.is_active == 1).all()
                    
                    if orgs:
                        # 创建表头
                        header = html.Tr([
                            html.Th('机构名称', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                            html.Th('机构代码', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                            html.Th('机构等级', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                            html.Th('上级机构', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                            html.Th('地址', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                            html.Th('联系人', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                            html.Th('联系电话', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                            html.Th('简称', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'})
                        ])
                        
                        # 创建表格行
                        rows = [header]
                        for org in orgs:
                            row = html.Tr([
                                html.Td(org.org_name or '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                                html.Td(org.org_code or '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                                html.Td(str(org.org_level) if org.org_level is not None else '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                                html.Td(org.parent_code or '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                                html.Td(org.address or '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                                html.Td(org.contact_person or '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                                html.Td(org.contact_phone or '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'}),
                                html.Td(org.short_name_c or '无', style={'color': 'white', 'border': '1px solid #0a2a43', 'padding': '8px'})
                            ])
                            rows.append(row)
                        
                        # 创建表格
                        table = html.Table(
                            rows,
                            style={
                                'width': '100%',
                                'borderCollapse': 'collapse',
                                'backgroundColor': '#001529',
                                'border': '1px solid #0a2a43'
                            }
                        )
                        
                        # 返回显示 modal 的样式和内容
                        return {'display': 'flex', 'position': 'fixed', 'top': '0', 'left': '0', 'width': '100%', 'height': '100%', 'backgroundColor': 'rgba(0,0,0,0.7)', 'zIndex': '1000', 'justifyContent': 'center', 'alignItems': 'center'}, "医疗机构列表", table
                    else:
                        # 返回显示 modal 的样式和提示信息
                        return {'display': 'flex', 'position': 'fixed', 'top': '0', 'left': '0', 'width': '100%', 'height': '100%', 'backgroundColor': 'rgba(0,0,0,0.7)', 'zIndex': '1000', 'justifyContent': 'center', 'alignItems': 'center'}, "医疗机构列表", html.Div("未找到任何机构信息", style={'color': 'white'})
                        
                except Exception as e:
                    print(f"DEBUG: 查询组织信息时出错: {str(e)}")
                    # 返回显示 modal 的样式和错误信息
                    return {'display': 'flex', 'position': 'fixed', 'top': '0', 'left': '0', 'width': '100%', 'height': '100%', 'backgroundColor': 'rgba(0,0,0,0.7)', 'zIndex': '1000', 'justifyContent': 'center', 'alignItems': 'center'}, "查询出错", html.Div(f"查询组织信息时出错: {str(e)}", style={'color': 'red'})
        
        # 如果触发的不是 hospital-count-link，则不更新
        return dash.no_update

# 关闭模态窗口
    @dash_app.callback(
        Output('org-info-modal', 'style', allow_duplicate=True),
        [Input('close-org-modal', 'n_clicks')],
        prevent_initial_call=True
    )
    def close_org_modal(n_clicks):
        if n_clicks:
            return {'display': 'none'}
        return dash.no_update


